<?php

namespace App\Http\Controllers\Mobile;

use App\Http\Requests\UserLoginFormRequest;
use App\Http\Requests\UserStoreFormRequest;
use App\Services\Mobile\SmsService;
use App\Services\Mobile\UserService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    private $userService;
    private $smsService;

    public function __construct(UserService $userService, SmsService $smsService)
    {
        $this->userService = $userService;
        $this->smsService = $smsService;
    }

    public function create()
    {
        return view('mobile.user.create');
    }

    public function store(UserStoreFormRequest $request)
    {
        $user = [
            'name' => $request->name,
            'sex' => intval($request->sex),
            'mobile' => $request->mobile,
//            'password' => encrypt($request->password),
        //users表的password字段太短，故还是选用md5
            'password' => md5($request->password),
        ];
        if (!$this->smsService->verify($user['mobile'], $request->code)) {
            return back()->with('error', '验证码错误');
        }

        $this->userService->store($user);
        return redirect()->route('user.login')->with('success', '注册成功');
    }

    public function login()
    {
        return view('mobile.user.login');
    }

    public function auth(UserLoginFormRequest $request)
    {
        $user = [
            'mobile' => $request->mobile,
            'password' => $request->password
        ];

        if ($this->userService->auth($user)) {
            return redirect(route('index'))->with('success', '登录成功');
        } else {
            return back()->with('error', '密码错误');
        }

    }

    public function logout()
    {
        $this->userService->logout();
        return redirect(route('index'))->with('info', '登出成功');
    }

    public function edit()
    {

    }

    public function update()
    {

    }

    //---

    public function me()
    {
        return view('mobile.user.me');
    }

    public function meSafe()
    {
        return view('mobile.user.meSafe');
    }

    public function editPassword()
    {
        return view('mobile.user.editPassword');
    }

}
